﻿using System.Windows.Controls;

namespace ICodeShare.UI.Controls.ValidationRules
{
    /// <summary>
    /// 绑定数据验证规则，范围值验证
    /// </summary>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///    xmlns:vals="http://schemas.extended.wpf.com/validations"
    /// 2.在xaml文件中指定Binding值的Converter
    /// <example>
    ///  <TextBox.Text>
    ///      <Binding Path="Age" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
    ///          <Binding.ValidationRules>
    ///              <vals:NumberRangeRule Min="0" Max="128"/>
    ///           </Binding.ValidationRules>
    ///      </Binding>
    ///   </TextBox.Text>
    /// </example>
    public class NumberRangeRule : ValidationRule
    {
        private int min = 0;

        public int Min
        {
            get { return min; }
            set { min = value; }
        }

        private int max = 100;

        public int Max
        {
            get { return max; }
            set { max = value; }
        }

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            int number;
            if (!int.TryParse((string)value, out number))
            {
                return new ValidationResult(false, "Invalid number format");
            }

            if (number < min || number > max)
            {
                return new ValidationResult(false, string.Format("Number out of range ({0} - {1})", min, max));
            }

            return ValidationResult.ValidResult;
        }
    }
}